package com.mxpio.erp.quality.service.impl;

import com.mxpio.erp.common.quality.entity.VEInspectionBillAssembleBadBack;
import com.mxpio.erp.common.quality.entity.VEInspectionBillPassRate;
import com.mxpio.erp.common.quality.entity.VEInspectionBillUnqualifiedParts;
import com.mxpio.erp.common.quality.service.VEInspectionBillSupplierPassRateService;
import com.mxpio.erp.common.quality.service.VEInspectionBillUnqualifiedPartsService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.lin.Linq;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class VEInspectionBillUnqualifiedPartsServiceImpl implements VEInspectionBillUnqualifiedPartsService {

    @Override
    @Transactional
    public List<VEInspectionBillUnqualifiedParts> list(Criteria c) {
        return JpaUtil.linq(VEInspectionBillUnqualifiedParts.class).where(c).list();
    }

    @Override
    @Transactional
    public Page<VEInspectionBillUnqualifiedParts> listPage(Pageable pageAble, Criteria c) {
        List<VEInspectionBillUnqualifiedParts> unqualifiedParts = new ArrayList<>();

        //存储拆分后的数据
        ArrayList<VEInspectionBillUnqualifiedParts> newList = new ArrayList<>();
        LocalDate today = LocalDate.now(); // 获取当前日期
        String year =Integer.toString(today.getYear()); // 获取年份
//        c.addCriterion("year", Operator.EQ, year);
        Linq linq =JpaUtil.linq(VEInspectionBillUnqualifiedParts.class);
        //查询到当年的所有数据
        List<VEInspectionBillUnqualifiedParts> list = linq.equal("year", year).list();
//        List<VEInspectionBillUnqualifiedParts> list = linq.aliasToBean(VEInspectionBillUnqualifiedParts.class).select("year","yearMonth", "unqualifiedType",
//                        linq.criteriaBuilder().sum(linq.root().get("unqualifiedQuantity")).alias("unqualifiedQuantity"))
//                .where(c)
////                .groupBy("year","yearMonth", "unqualifiedType")
//                .list();
        //拆分多类型
        for (VEInspectionBillUnqualifiedParts veInspectionBillUnqualifiedParts : list){
            if (veInspectionBillUnqualifiedParts.getUnqualifiedType() != null){
                String unqualifiedType = veInspectionBillUnqualifiedParts.getUnqualifiedType();
                String[] types = unqualifiedType.split(",");
                if (types.length > 1) {
                    for (String type : types) {
                        VEInspectionBillUnqualifiedParts parts = new VEInspectionBillUnqualifiedParts();
                        parts.setYear(veInspectionBillUnqualifiedParts.getYear());
                        parts.setYearMonth(veInspectionBillUnqualifiedParts.getYearMonth());
                        parts.setUnqualifiedType(type);
                        parts.setUnqualifiedQuantity(veInspectionBillUnqualifiedParts.getUnqualifiedQuantity());
                        newList.add(parts);
                    }
                }else {
                    newList.add(veInspectionBillUnqualifiedParts);
                }
            }
        }
        //得到去重后的所有类型
        Set<String> seenTypes = new HashSet<>();
        List<VEInspectionBillUnqualifiedParts> uniqueList = new ArrayList<>();
        for (VEInspectionBillUnqualifiedParts item : newList) {
            if (seenTypes.add(item.getUnqualifiedType())) {
                uniqueList.add(item);
            }
        }

        BigDecimal totalYear = BigDecimal.ZERO;
        //取全年的不合格数量
        for (VEInspectionBillUnqualifiedParts veInspectionBillUnqualifiedParts : newList){
            totalYear = totalYear.add(veInspectionBillUnqualifiedParts.getUnqualifiedQuantity());
        }
        //计算各个类型当年的不合格数量
        for (VEInspectionBillUnqualifiedParts veInspectionBillUnqualifiedParts : uniqueList){
            VEInspectionBillUnqualifiedParts parts = new VEInspectionBillUnqualifiedParts();
            parts.setUnqualifiedType(veInspectionBillUnqualifiedParts.getUnqualifiedType());//类型
            BigDecimal typeTotalYear = BigDecimal.ZERO;
            for (VEInspectionBillUnqualifiedParts veInspectionBillUnqualifiedParts1 : newList){
                if (StringUtils.equals(parts.getUnqualifiedType(),veInspectionBillUnqualifiedParts1.getUnqualifiedType())){
                    typeTotalYear = typeTotalYear.add(veInspectionBillUnqualifiedParts1.getUnqualifiedQuantity());
                }
            }
            parts.setLastYear(typeTotalYear.divide(totalYear, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)));//全年累计占比

            //计算上个月的占比
            //上月总数量
            LocalDate lastMonth = today.minusMonths(1);
            // 格式化日期为 "yyyy-MM" 格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
            String formattedLastMonth = lastMonth.format(formatter);
            //上个月所有类型不合格数量
            BigDecimal lastMonthNum= BigDecimal.ZERO;
            BigDecimal lastMonthNumType= BigDecimal.ZERO;
            for (VEInspectionBillUnqualifiedParts veInspectionBillUnqualifiedParts1 : newList){
                if (StringUtils.equals(formattedLastMonth,veInspectionBillUnqualifiedParts1.getYearMonth())){
                    lastMonthNum = lastMonthNum.add(veInspectionBillUnqualifiedParts1.getUnqualifiedQuantity());
                    //上个月类型的补一个占比
                    if (StringUtils.equals(parts.getUnqualifiedType(),veInspectionBillUnqualifiedParts1.getUnqualifiedType())){
                        lastMonthNumType = lastMonthNumType.add(veInspectionBillUnqualifiedParts1.getUnqualifiedQuantity());
                    }
                }
            }
            if (lastMonthNum.compareTo(BigDecimal.ZERO) > 0) {
                parts.setLastMonth(lastMonthNumType.divide(lastMonthNum, 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)));//上月累计占比
            }else {
                parts.setLastMonth(BigDecimal.ZERO);
            }

            unqualifiedParts.add(parts);
    }
        return new PageImpl<>(unqualifiedParts, pageAble, unqualifiedParts.size());
    }

    @Override
    @Transactional
    public Result<?> getlist() {
        // 获取当前日期
        LocalDate today = LocalDate.now();

        // 创建一个DateTimeFormatter来格式化日期为YYYY-MM格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

        // 使用formatter格式化today日期
        String formattedDate = today.format(formatter);
        Criteria criteria = Criteria.create();
        criteria.addCriterion("yearMonth ",Operator.EQ, formattedDate);
        List<VEInspectionBillUnqualifiedParts> newList  = new ArrayList<>();
        Linq linq =JpaUtil.linq(VEInspectionBillUnqualifiedParts.class);
        List<VEInspectionBillUnqualifiedParts> list = linq.equal("yearMonth", formattedDate).list();
        /**
        List<VEInspectionBillUnqualifiedParts> list1 = linq.where(criteria).list();
        List<VEInspectionBillUnqualifiedParts> list = linq.aliasToBean(VEInspectionBillUnqualifiedParts.class).select("yearMonth","unqualifiedType",
                        linq.criteriaBuilder().sum(linq.root().get("unqualifiedQuantity")).alias("unqualifiedQuantity"))
//                        linq.criteriaBuilder().sum(linq.root().get("itemCode")).alias("itemCode"),
//                        linq.criteriaBuilder().sum(linq.root().get("itemName")).alias("itemName"),
//                        linq.criteriaBuilder().sum(linq.root().get("drawingNo")).alias("drawingNo"))
                .where(criteria)
//                .groupBy("yearMonth", "unqualifiedType")
                .groupBy("yearMonth")
                .list();
         */

        for (VEInspectionBillUnqualifiedParts veInspectionBillUnqualifiedParts : list){
            if (veInspectionBillUnqualifiedParts.getUnqualifiedType() != null){
                String unqualifiedType = veInspectionBillUnqualifiedParts.getUnqualifiedType();
                String[] types = unqualifiedType.split(",");
                if (types.length > 1) {
                    for (String type : types) {
                        VEInspectionBillUnqualifiedParts parts = new VEInspectionBillUnqualifiedParts();
                        parts.setYear(veInspectionBillUnqualifiedParts.getYear());
                        parts.setYearMonth(veInspectionBillUnqualifiedParts.getYearMonth());
                        parts.setUnqualifiedType(type);
                        parts.setUnqualifiedQuantity(veInspectionBillUnqualifiedParts.getUnqualifiedQuantity());
                        newList.add(parts);
                    }
                }else {
                    newList.add(veInspectionBillUnqualifiedParts);
                }
            }
        }
        Map<String, BigDecimal> exceptionTypeMap = new HashMap<>();

        // 遍历列表，累加exceptionQuantity
        for (VEInspectionBillUnqualifiedParts item : newList) {
            exceptionTypeMap.merge(item.getUnqualifiedType(), item.getUnqualifiedQuantity(), BigDecimal::add);
        }

        // 将结果放入新的List中，这里使用Map作为列表的元素以存储结果
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Map.Entry<String, BigDecimal> entry : exceptionTypeMap.entrySet()) {
            Map<String, Object> resultEntry = new HashMap<>();
            resultEntry.put("unqualifiedType", entry.getKey());
            resultEntry.put("unqualifiedQuantity", entry.getValue());
            resultList.add(resultEntry);
        }
        List<VEInspectionBillUnqualifiedParts> unqualifiedParts = new ArrayList<>();
        for (Map<String, Object> resultEntry : resultList) {
            VEInspectionBillUnqualifiedParts veInspectionBillUnqualifiedParts = new VEInspectionBillUnqualifiedParts();
            veInspectionBillUnqualifiedParts.setUnqualifiedType(resultEntry.get("unqualifiedType").toString());
            veInspectionBillUnqualifiedParts.setUnqualifiedQuantity(new BigDecimal(resultEntry.get("unqualifiedQuantity").toString()));
            unqualifiedParts.add(veInspectionBillUnqualifiedParts);
        }
        return Result.OK(unqualifiedParts);

    }
}
